package ws.jdbc.concurrent.driver.sqlserver.tds;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ws.jdbc.concurrent.driver.sqlserver.tds.datastreamtypes.US_VARCHAR;

/**
 * Handles the {@code TABNAME} token reading process.
 *
 * <p>
 * Used to send the table name to the client only when in browser mode or from
 * {@code sp_cursoropen}.
 * </p>
 *
 * <p>
 * <a href="http://msdn.microsoft.com/en-us/library/dd340017">Reference</a>
 * </p>
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class TabNameTokenReader extends TokenReader {

  /**
   * The actual data length, in bytes, of the TABNAME token stream.
   * The length does not include token type and length field.
   */
  private short length;
  private byte numParts;
  private List<US_VARCHAR> partList;

  public TabNameTokenReader(final ByteBuffer stream) {
    super(stream);
  }

  @Override
  int read() throws IOException {
    // Length
    length = stream.getShort();
    // AllTableNames
    //  NumParts
    numParts = stream.get();
    //  PartName
    partList = new ArrayList<US_VARCHAR>(numParts);
    for (int i = 0; i < numParts; ++i) {
      partList.add(vldsReader.readUSVarChar());
    }
    return 3 + vldsReader.getBytesRead();
  }

  /**
   * Get the table name.
   *
   * @return table name.
   */
  public String getTableName() {
    return partList.get(0).toString();
  }

  /**
   * Token as a {@code String}.
   *
   * @return token fields as a {@code String}.
   */
  @Override
  public String toString() {
    return "TabNameTokenReader{"
            + "\n  Length=" + length
            + "\n  NumParts=" + numParts
            + "\n  Parts=" + partList
            + "\n}\n";
  }
}
